<?php

namespace Xin\Setting;

use Xin\Setting\Contracts\Serializer;

abstract class DatabaseRepository extends AbstractRepository
{
	/**
	 * @var Serializer
	 */
	protected $serializer;

	/**
	 * @param array $config
	 * @param Serializer $serializer
	 */
	public function __construct(array $config, Serializer $serializer)
	{
		parent::__construct($config);
		$this->serializer = $serializer;
	}

	/**
	 * @return Serializer
	 */
	public function getSerializer()
	{
		return $this->serializer;
	}

	/**
	 * @param Serializer $serializer
	 * @return void
	 */
	public function setSerializer(Serializer $serializer)
	{
		$this->serializer = $serializer;
	}

	/**
	 * 获取受支持的搜索字段
	 * @return array
	 */
	protected function getSearchFields()
	{
		return $this->getConfig('search_fields', [
			"id", "title", "name", "alias", "type", "group", "remark", "sort",
			"status", "system", "display", "public", "updated_at", "created_at",
		]);
	}

	/**
	 * 解析排序
	 * @param mixed $orders
	 * @return array
	 */
	protected function resolveOrders($orders)
	{
		if (!is_array($orders)) {
			$orders = [$orders];
		}

		$result = [];
		foreach ($orders as $order) {
			if (is_string($order)) {
				$order = explode(" ", $order, 2);
			}

			$result[] = $order;
		}

		return $result;
	}
}
